(function ($, _window) {
  var today = new Date(),
    todayDay = today.getDate(),
    todayMon = today.getMonth() + 1,
    todayYe = today.getFullYear() - 18,
    areU18 = new Date(todayYe, todayMon, todayDay),
    myProfileEmailRegex = /^([a-zA-Z\d_\.\-\+'%])+\@(([a-zA-Z\d\-])+\.)+([a-zA-Z\d]{2,4})+$/;

  var bValidatorOptions = {
    showCloseIcon: false,
    showErrMsgSpeed: "fast",
    errorClass: "error error-state",
    position: {
      x: 'right',
      y: 'bottom'
    },
    offset: {
      x: 10,
      y: 0
    }
  };

  var bvalidator_profile_form = $('.profile_form');

  bvalidator_profile_form.bValidator(bValidatorOptions).find('button[id*=lbSubmit]').click(function () {

    $('#success_message').removeClass("error");

    $('.registration-page .collapse').each(function () {
      $(this).addClass('show');
    });

    $('.registration-page .fas.fa-plus').removeClass('fa-plus').addClass('fa-minus');

    // My Profile Edit Page
    $('.my-profile-page .collapse').addClass('show');
    $('.my-profile-page [data-toggle=collapse]').removeClass('collapsed');

    if (!$(this).closest(bvalidator_profile_form).data('bValidator').validate() /*|| $(".unverified-email").length || $(".unverified-address").length*/ ) {

      if ($(this).closest(bvalidator_profile_form).find('input[id*=AgreeToTerms]').length) {
        $(this).closest(bvalidator_profile_form).find('input[id*=AgreeToTerms]').next('div.bVErrMsgContainer').remove();
        $('input[id*=AgreeToTerms]').prop("checked", false);
        $('input[id*=AgreeToTerms]').attr('aria-describedby', 'terms-err');
        $('.terms-errmsg').show();
        $("#terms-label").addClass("bvalidator_error error-state");
      }

      //if ($(".unverified-email").length || $(".unverified-address").length) {
      //  $(".unverified-email").addClass("bvalidator_error error-state");
      //  $(".unverified-address").addClass("bvalidator_error error-state");
      //}

      var errorField = $(".error-state:first");

      if (errorField.length) {
        $(".form-group").map(function () {
          var id = $(this).find("input").attr("id");
          $(this).find(".bvalidator_errmsg").attr("id", id + "_err");
        });

        $("html, body").stop().animate({
            scrollTop: $(errorField).offset().top - 100
          },
          50,
          'swing');
        if (errorField.children("input:first").length) {
          errorField.children("input:first").focus();
        } else {
          errorField.focus();
        }
      }
      return false;

    } else {
      bvalidator_profile_form.removeClass("error");
      var homeLoader = $('body').loadingIndicator({
        useImage: false,
      }).data("loadingIndicator");
      $('body').addClass('spinner');
      homeLoader.show();
      bvalidator_profile_form.submit();
      return false;
    }
  });

  /**
   * Validates an address or name
   * @param  {String} address to validate
   * @return {Bool}       validation state
   */
  validaddressorname = function (code, type) {
    code = code.toString();
    if (type.toString() == "address") {
      var regexAddr = /[^a-zA-Z0-9\s-,'\.#\/]+/g;
    } else {
      var regexAddr = /[^a-zA-Z\s-']+/g;
    }
    return !regexAddr.test(code);
  };

  /**
   * Validates a middle initial
   * @param {String} middle initial to be tested
   * @returns {Bool} validation state
   */
  validmiddleinitial = function (code) {
    code = code.toString();
    var regexAddr = /[^a-zA-Z]+/g;
    return !regexAddr.test(code);
  };

  /**
   * Validates a suffix
   * @param {String} suffix to be tested
   * @returns {Bool} validation state
   */
  validsuffix = function (code) {
    code = code.toString();
    var regexAddr = /[^a-zA-Z]+/g;
    return !regexAddr.test(code);
  };

  /**
   * Validates an email address
   * @param {string} email address to validate
   * @return {bool} validation state
   */

  validemailmyprofile = function (code) {
    code = code.toString();
    return myProfileEmailRegex.test(code);
  };

  /**
   * Validates a phone number
   * @param  {String} num Phone nuumber string to validate
   * @return {Bool}       validation state
   */
  validphone = function (num) {
    num = num.toString();
    var stripped = num.replace(/[\D]/gi, '');
    return (num.length <= 14 &&
      /^\d{10}$/.test(stripped) &&
      /^[0-9 \)\(-]+$/g.test(num) &&
      !/[a-z]/i.test(num));
  };
  /**
   * Validates a postal code
   * @param  {String} code Postal code string to validate
   * @return {Bool}        Validation state
   */
  validpostalcode = function (code) {
    code = code.toString();
    if ($('#objBody_content_0_leftcolumn_0_hdnValidZip').val() == 'true' ||
      $('#objBody_content_0_pagecontent_0_hdnValidZip').val() == 'true') {
      return (code.length <= 15 && /[a-z0-9\-\s]/i.test(code));
    }
  };

  validDLNum = function (code) {
    var isValid = false;
    //4 num
    isValid = code.match(/\d/g) == null ? false : code.match(/\d/g).length >= 4;
    //2 alpha
    isValid = (code.match(/[a-zA-Z]/g) == null ? false : isValid && code.match(/[a-zA-Z]/g).length <= 2);
    //3 & 4 num
    isValid = (code.match(/^..\d\d/) == null ? false : isValid && code.match(/^..\d\d/));
    //max length
    isValid = isValid && code.length < 10;
    return isValid;
  }
  minage18 = function (code) {
    var dobDateMo = code.split('/')[0],
      dobDateDa = code.split('/')[1],
      dobDateYe = code.split('/')[2],
      dobMilli = new Date(dobDateYe, dobDateMo, dobDateDa);
    // dobMilli = parseInt(dob.getTime(), 10);
    if (dobMilli <= areU18 && dobDateYe >= 1900) {
      return true;
    } else {
      return false;
    }
  };

  passcontains = function (code) {

    var reqCount = 0,
      atLeastOneNum = /(?=(.*[\d]){1,})+/,
      atLeastOneCap = /(?=(.*[A-Z]){1,})+/,
      atLeastOneLow = /(?=(.*[a-z]){1,})+/,
      atLeastOneSym = /(?=(.*[@#$%!]){1,})+/,
      emailAdd = $('#objBody_content_0_pagecontent_0_txtEmail').length > 0 ?
      $('#objBody_content_0_pagecontent_0_txtEmail') :
      $('#registration-email-field'),
      notNewEmail = $(emailAdd).val().split('@')[0],
      notNewEmail = notNewEmail.replace(/([^a-zA-Z0-9]+)/g, '\\$1'),
      notNewEmail = new RegExp(notNewEmail, ''),
      notCurEmail = $('#objBody_content_0_pagecontent_0_lblCurrentEmail').next('p').text(),
      notCurEmail = notCurEmail.replace(/([^a-zA-Z0-9]+)/g, '\\$1'),
      notCurEmail = new RegExp(notCurEmail, 'g');
    if (notCurEmail.test(code)) {
      reqCount = 0;
    }
    if (notNewEmail.test(code)) {
      reqCount = 0;
    }
    if (atLeastOneNum.test(code)) {
      reqCount++;
    }
    if (atLeastOneCap.test(code)) {
      reqCount++;
    }
    if (atLeastOneLow.test(code)) {
      reqCount++;
    }
    if (atLeastOneSym.test(code)) {
      reqCount++;
    }

    if (reqCount >= 2 && code.length >= 8) {
      // alert('woo');
      return true;

    } else {

      // alert('noo');
      return false;

    }

  };

  var dobField = document.getElementById("objBody_content_0_leftcolumn_0_dob1");

  function checkDateValue(str, max, maxChar) {
    if (str.length > maxChar) str = str.substring(maxChar);
    if (str.charAt(0) !== '0' || str == '00') {
      var num = parseInt(str);
      if (isNaN(num) || num <= 0) num = 1;
      if (max !== false) {
        if (num > max) num = max;
        if (maxChar === 2) {
          str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
        } else if (maxChar === 4) {
          str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? max.toString().charAt(0) + num : num.toString();
        }
      }
    }
    return str;
  }

  if (dobField !== null) {
    dobField.addEventListener('keyup',
      function (e) {
        if (e.keyCode !== 46 &&
          e.keyCode !== 40 &&
          e.keyCode !== 39 &&
          e.keyCode !== 38 &&
          e.keyCode !== 37 &&
          e.keyCode !== 36 &&
          e.keyCode !== 35 &&
          e.keyCode !== 16 &&
          e.keyCode !== 9 &&
          e.keyCode !== 8) {
          this.type = 'text';
          var input = this.value;
          var values = input.split('/').map(function (v) {
            return v.replace(/\D/g, '')
          });
          if (values[0]) values[0] = checkDateValue(values[0], 12, 2);
          if (values[1]) values[1] = checkDateValue(values[1], 31, 2);
          //notice that the "max" value passed to checkDateValue is the current year -- so dates beyond the current year will auto-correct to the current year. You can change new Date().getFullYear() to false and not have the year auto-corrected. The same applies to the month and day values above.
          if (values[2]) values[2] = checkDateValue(values[2], new Date().getFullYear(), 4);
          var output = values.map(function (v, i) {
            return v.length >= 2 && i < 2 ? v + '/' : v;
          });
          this.value = output.join('').substr(0, 10);
        }
      });
  }

  // Bootstrap Form Validation

  $.fn.extend({
    passwordValidation: function (_options) {
      //var _unicodeSpecialSet = "^\\x00-\\x1F\\x7F\\x80-\\x9F0-9A-Za-z"; //All chars other than above (and C0/C1)
      var CHARSETS = {
        upperCaseSet: "A-Z", //All UpperCase (Acii/Unicode)
        lowerCaseSet: "a-z", //All LowerCase (Acii/Unicode)
        digitSet: "0-9", //All digits (Acii/Unicode)
        specialSet: "\\x20-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E\\x80-\\xFF", //All Other printable Ascii
      };
      var _defaults = {
        minLength: 8, //Minimum Length of password
        minUpperCase: 1, //Minimum number of Upper Case Letters characters in password
        minLowerCase: 1, //Minimum number of Lower Case Letters characters in password
        minDigits: 1, //Minimum number of digits characters in password
        minSpecial: 1, //Minimum number of special characters in password
        maxRepeats: 5, //Maximum number of repeated alphanumeric characters in password dhgurAAAfjewd <- 3 A's
        maxConsecutive: 3, //Maximum number of alphanumeric characters from one set back to back
        noUpper: false, //Disallow Upper Case Lettera
        noLower: false, //Disallow Lower Case Letters
        noDigit: false, //Disallow Digits
        noSpecial: false, //Disallow Special Characters
        //NOT IMPLEMENTED YET allowUnicode: false,  //Switches Ascii Special Set out for Unicode Special Set
        failRepeats: true, //Disallow user to have x number of repeated alphanumeric characters ex.. ..A..a..A.. <- fails if maxRepeats <= 3 CASE INSENSITIVE
        failConsecutive: true, //Disallow user to have x number of consecutive alphanumeric characters from any set ex.. abc <- fails if maxConsecutive <= 3
        confirmField: undefined
      };

      //Ensure parameters are correctly defined
      if ($.isFunction(_options)) {
        _options = {};
      }

      //concatenate user options with _defaults 
      _options = $.extend(_defaults, _options);
      if (_options.maxRepeats < 2) _options.maxRepeats = 2;

      function charsetToString() {
        return CHARSETS.upperCaseSet + CHARSETS.lowerCaseSet + CHARSETS.digitSet + CHARSETS.specialSet;
      }

      //GENERATE ALL REGEXs FOR EVERY CASE
      function buildPasswordRegex() {
        var cases = [];
        var requiredLength;

        //if(_options.allowUnicode) CHARSETS.specialSet = _unicodeSpecialSet;
        if (_options.noUpper)
          cases.push({
            "regex": "(?=" + CHARSETS.upperCaseSet + ")",
            "message": "Password can't contain an uppercase letter"
          });
        else
          cases.push({
            "regex": "(?=" +
              ("[" + CHARSETS.upperCaseSet + "][^" + CHARSETS.upperCaseSet + "]*").repeat(_options.minUpperCase) +
              ")",
            "message": "Password must contain at least " + _options.minUpperCase + " capital letter.",
            "weight": .5
          });
        if (_options.noLower)
          cases.push({
            "regex": "(?=" + CHARSETS.lowerCaseSet + ")",
            "message": "Password can't contain a lowercase letter"
          });
        else
          cases.push({
            "regex": "(?=" +
              ("[" + CHARSETS.lowerCaseSet + "][^" + CHARSETS.lowerCaseSet + "]*").repeat(_options.minLowerCase) +
              ")",
            "message": "Password must contain at least " + _options.minLowerCase + " lowercase letters.",
            "weight": .5
          });
        if (_options.noDigit)
          cases.push({
            "regex": "(?=" + CHARSETS.digitSet + ")",
            "message": "Password can't contain a number"
          });
        else
          cases.push({
            "regex": "(?=" +
              ("[" + CHARSETS.digitSet + "][^" + CHARSETS.digitSet + "]*").repeat(_options.minDigits) +
              ")",
            "message": "Password must contain at least " + _options.minDigits + " number.",
            "weight": .5
          });
        if (_options.noSpecial)
          cases.push({
            "regex": "(?=" + CHARSETS.specialSet + ")",
            "message": "Password can't contain a special character"
          });
        else
          cases.push({
            "regex": "(?=" +
              ("[" + CHARSETS.specialSet + "][^" + CHARSETS.specialSet + "]*").repeat(_options.minSpecial) +
              ")",
            "message": "Password must contain at least " + _options.minSpecial + " symbol.",
            "weight": .5
          });

        return cases;
      }

      var _cases = buildPasswordRegex();

      var _element = this;
      var confirmField = (_options.confirmField != undefined) ? $(_options.confirmField) : undefined;

      //Field validation on every captured event
      function validateField() {
        var failedCases = [];
        var success = true;
        var score = 0;

        requiredLength = {
          "regex": "[" + charsetToString() + "]{" + _options.minLength + ",}",
          "message": "Password must contain at least " + _options.minLength + " characters."
        };

        //Evaluate all verbose cases

        if ($("#currentPassword-field").val() == "") {
          $("#currentPassword-field").closest(".form-group").addClass("error-state");
          $("<div id=\"currentPassword-field_err\" class=\"bvalidator_errmsg\" aria-live=\"polite\" aria-atomic=\"true\" style=\"visibility: visible;\"><div class=\"validation-error small font-weight-bold mb-0\">" + passwordValidationMessages.currentPasswordEmpty + "</div></div>").insertAfter("#currentPassword-field");
          success = false;
        }

        if (confirmField.val() == "") {
          $("#confirmPassword-field").closest(".form-group").addClass("error-state");
          $("<div id=\"confirmPassword-field_err\" class=\"bvalidator_errmsg\" aria-live=\"polite\" aria-atomic=\"true\" style=\"visibility: visible;\"><div class=\"validation-error small font-weight-bold mb-0\">" + passwordValidationMessages.confirmPasswordEmpty + "</div></div>").insertAfter("#confirmPassword-field");
          success = false;
        }

        // Display error if password is email
        if ($("#createPassword-field").val().search(new RegExp("(?=^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}$)", "gi")) > -1) {
          $("#createPassword-field").closest(".form-group").addClass("error-state");
          $("<div id=\"currentPassword-field_err\" class=\"bvalidator_errmsg\" aria-live=\"polite\" aria-atomic=\"true\" style=\"visibility: visible;\"><div class=\"validation-error small font-weight-bold mb-0\">" + passwordValidationMessages.passwordCannotBeEmail + "</div></div>").insertAfter("#createPassword-field");
          success = false;
        }

        if ($(_element).val() == "") {
          $(_element).closest(".form-group").addClass("error-state");
          $("<div id=\"createPassword-field_err\" class=\"bvalidator_errmsg\" aria-live=\"polite\" aria-atomic=\"true\" style=\"visibility: visible;\"><div class=\"validation-error small font-weight-bold mb-0\">" + passwordValidationMessages.newPasswordEmpty + "</div></div>").insertAfter("#createPassword-field");
          success = false;
        } else {
          $.each(_cases,
            function (_i, _case) {
              if ($(_element).val().search(new RegExp(_case.regex, "g")) == -1 && score < 1) {
                failedCases.push(_case.message);
              } else {
                score += _case.weight;
              }
            });

          //Clear error array if weight score is equal to or higher than 1
          if (score >= 1) {
            failedCases.length = 0;
          }

          //Separate check for password length
          if ($(_element).val().search(new RegExp(requiredLength.regex, "g")) == -1) {
            failedCases.push(requiredLength.message);
          }

          if (_options.failRepeats &&
            $(_element).val().search(new RegExp("(.)" + (".*\\1").repeat(_options.maxRepeats - 1), "gi")) != -1) {
            failedCases.push("Password can not contain " + _options.maxRepeats + " of the same character.");
          }
          if (_options.failConsecutive &&
            $(_element).val().search(new RegExp("(?=(.)" + ("\\1").repeat(_options.maxConsecutive) + ")", "g")) != -1) {
            failedCases.push("Password can't contain the same character more than " +
              _options.maxConsecutive +
              " times in a row.");
          }

          //Determine if password is valid (score must be 1 and length greater than minLength)
          var validPassword = (score >= 1) && ($(_element).val().length >= _options.minLength);
          var fieldsMatch = true;
          fieldsMatch = (confirmField.val() == $(_element).val());

          if (!validPassword) {
            $(_element).closest(".form-group").addClass("error-state");
          }

          if ($(_element).val() != "") {
            if (!validPassword) {
              var errors = "";
              $.each(failedCases,
                function (key, value) {
                  errors += "<div class=\"validation-error small font-weight-bold mb-0\">" + value + "</div>";
                });
              $("<div id=\"createPassword-field_err\" class=\"bvalidator_errmsg\" aria-live=\"polite\" aria-atomic=\"true\" style=\"visibility: visible;\">" + errors + "</div>").insertAfter("#createPassword-field");
              $(_element).closest(".form-group").addClass("error-state");
            }
          }

          if (validPassword && fieldsMatch) $("#confirmPassword-field").removeClass("is-invalid");

          if (confirmField.val() != "") {
            if (!fieldsMatch) {
              $("#confirmPassword-field").closest(".form-group").addClass("error-state");
              $("<div id=\"confirmPassword-field_err\" class=\"bvalidator_errmsg\" aria-live=\"polite\" aria-atomic=\"true\" style=\"visibility: visible;\"><div class=\"validation-error small font-weight-bold mb-0\">" + passwordValidationMessages.confirmPasswordInvalid + "</div></div>").insertAfter("#confirmPassword-field");
            }
          }

          if (!validPassword || !fieldsMatch) {
            success = false;
          }
        }

        return success;
      }

      var form = $('.password-form');
      var fsubmit = $('.password-form .btn-submit');

      fsubmit.click(function (event) {
        $(".error-state").removeClass("error-state");
        $(".password-form .bvalidator_errmsg").remove();
        if (!validateField()) {
          event.preventDefault();
          event.stopPropagation();
          $(".form-group").map(function () {
            var id = $(this).find("input").attr("id");
            $(this).find(".bvalidator_errmsg").attr("id", id + "_err");
          });
          $(".error-state:first").children("input").first().focus();
        }
        form.addClass('was-validated');
        $('#email-field').val('');
      });
    }
  });

  //Support for auto-tabbing when field maxlength is reached and user continues to enter characters
  //Accepts an array of div IDs that contain fields that you want auto-tabbed
  function autoTab(containerIds) {
    containerIds.forEach(function (containerId) {
      var container = document.getElementById(containerId);
      if (container !== null) {
        container.onkeyup = function (e) {
          var target = e.srcElement;
          if (target.type === "text") {
            var maxLength = parseInt(target.attributes["maxlength"].value, 10);
            var myLength = target.value.length;
            if (myLength >= maxLength && !(e.keyCode === 40 || e.keyCode === 39 || e.keyCode === 38 || e.keyCode === 37 || e.keyCode === 36 || e.keyCode === 35 || e.keyCode === 16 || e.keyCode === 9)) {
              $(target).parent().next().find('input').focus();
            }
          }
        };
      }
    });
  }

  $(document).ready(function () {
    autoTab(["scratchers-fields", "slp-fields", "f5-fields"]);
  });

  $(document).ready(function () {
    $("#createPassword-field").passwordValidation({
      "confirmField": "#confirmPassword-field"
    });
  });

  var loginForm = $('.sign-in--form');
  var loginSubmit = $('.sign-in--form .btn-submit');
  var contactForm = $('#contact-form');
  var contactSubmit = $('#contact-submit');
  var scrathersForm = $('#scratchers2ndchance');
  var superlottoForm = $('#superlotto2ndchance');
  var fantasyForm = $('#fantasy2ndchance');
  var scratchersSubmit = $('#scratchers2ndchance .btn-submit');
  var superlottoSubmit = $('#superlotto2ndchance .btn-submit');
  var fantasySubmit = $('#fantasy2ndchance .btn-submit');
  var alert = $('.alert');
  var valid = $('.valid-feedback');
  var invalid = $('.invalid-feedback');

  loginSubmit.click(function (event) {
    loginForm.removeClass('error');

    if (loginForm[0].checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
      loginForm.addClass('error');
    }
    loginForm.addClass('was-validated');
  });

  scratchersSubmit.click(function (event) {
    scrathersForm.removeClass('is-invalid');

    if (scrathersForm[0].checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
      scrathersForm.addClass('is-invalid');
    } else {
      scrathersForm.addClass('is-valid');
    }
    scrathersForm.addClass('serverside-validated, was-validated');
  });

  superlottoSubmit.click(function (event) {
    superlottoForm.removeClass('is-invalid');

    if (superlottoForm[0].checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
      superlottoForm.addClass('is-invalid');
    } else {
      superlottoForm.addClass('is-valid');
    }
    superlottoForm.addClass('was-validated');
  });

  fantasySubmit.click(function (event) {
    fantasyForm.removeClass('is-invalid');

    if (fantasyForm[0].checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
      fantasyForm.addClass('is-invalid');
    } else {
      fantasyForm.addClass('is-valid');
    }
    fantasyForm.addClass('was-validated');
  });

  contactSubmit.click(function (event) {

    var invalidAlerts = $('.invalid-feedback');

    contactForm.removeClass('error');

    if (contactForm[0].checkValidity() === false) {

      event.preventDefault();
      event.stopPropagation();
      contactForm.addClass('error');
      alert.addClass('error');

      $('.form-control:invalid').first().focus();

    } else {
      alert.removeClass('error');
    }
    contactForm.addClass('was-validated');

    invalidAlerts.each(function (i, e) {
      var errorMsg = $(e).html();
      if ($(e).is(':visible')) {
        $(e).next().html(errorMsg);
      }
    });

  });

  $('#contact-topic').change(function () {
    var selectedTopic = $("#contact-topic").val();
    var subjectsSelect = $('#contact-subject');
    var selectedSubjectDefault = subjectsSelect.find('option').first().text();
    if (selectedTopic != null && selectedTopic != '') {
      $.getJSON(subjectsSelect.data('url'), {
        topicid: selectedTopic,
        defaultSubject: selectedSubjectDefault
      }, function (subjects) {
        if (subjects != null && !jQuery.isEmptyObject(subjects)) {
          subjectsSelect.empty();
          $.each(subjects, function (index, subject) {
            subjectsSelect.append($('<option/>', {
              value: subject.Value,
              text: subject.Text
            }));
          });
        };
      });
    }

    subjectsSelect.empty();
    subjectsSelect.append($('<option value="" disabled selected>Please select a Subject</option>'));
    // subjectsSelect.find('option').first().attr('disabled').attr('hidden').val(null);
  });


  //Polyfill for String.repeat support
  if (!String.prototype.repeat) {
    String.prototype.repeat = function (count) {
      'use strict';
      if (this == null)
        throw new TypeError('can\'t convert ' + this + ' to object');

      var str = '' + this;
      // To convert string to integer.
      count = +count;
      // Check NaN
      if (count != count)
        count = 0;

      if (count < 0)
        throw new RangeError('repeat count must be non-negative');

      if (count == Infinity)
        throw new RangeError('repeat count must be less than infinity');

      count = Math.floor(count);
      if (str.length == 0 || count == 0)
        return '';

      // Ensuring count is a 31-bit integer allows us to heavily optimize the
      // main part. But anyway, most current (August 2014) browsers can't handle
      // strings 1 << 28 chars or longer, so:
      if (str.length * count >= 1 << 28)
        throw new RangeError('repeat count must not overflow maximum string size');

      var maxCount = str.length * count;
      count = Math.floor(Math.log(count) / Math.log(2));
      while (count) {
        str += str;
        count--;
      }
      str += str.substring(0, maxCount - str.length);
      return str;
    };
  }

  // Agree to Terms Checkbox 
  $('#terms-label').click(function () {
    $('#terms-check').removeClass('error');
    if ($('input[id*=AgreeToTerms]').prop('checked') == true) {
      $('input[id*=AgreeToTerms]').removeAttr('data-bvalidator');
    } else {
      $('input[id*=AgreeToTerms]').attr('data-bvalidator', 'required');
      $('#terms-err').hide();
    }
  });

  // Submit serverside validated forms refocus

  if ($('body.my-account').length || $('body.my-account-page').length) {
    if ($('form.serverside-validated.was-validated').length) {
      $('#secondChance.my-account--card .collapse').collapse('show');

      $('form.serverside-validated.was-validated').find('input[type="text"]').first().focus();
    }

    if ($('form.serverside-validated.is-invalid').length || $('form.serverside-validated.is-valid').length) {
      $('input[type="text"]').on('focus', function () {
        $(this).val('');
      });
      $("html, body").stop().animate({
        scrollTop: $('.was-validated').offset().top - 25
      }, 50, 'swing');
    }

    if ($('.resubmit').length) {
      $('#secondChance.my-account--card .collapse').collapse('show');
      $("html, body").stop().animate({
        scrollTop: $('#scratchers2ndchance').offset().top - 25
      }, 50, 'swing');
    }
  }


  // Forgot Password email
  $("#forgot-password-submit").on('click', function () {
    if ($('#email-field').val() == "") {
      setTimeout(function () {
        $('.bvalidator_errmsg').attr('id', 'bvalidator_errmsg');
        $('.bVErrMsgContainer').attr('role', 'alert');
        $('#email-field').focus();
      }, 500);
    }
  });

  //forgot password reset form
  var bvalidator_password_request_form = $('#forgot-password-request');
  bvalidator_password_request_form.bValidator(bValidatorOptions);

  $(bvalidator_password_request_form).on('click', function () {
    if ($('#email-field').val() == "") {
      $('.bvalidator_errmsg').attr('id', 'bvalidator_errmsg');
      $('.bVErrMsgContainer').attr('role', 'alert');
      $('#email-field').focus();
    }
  });

  //auto-dismiss top-of-page alerts after giving screen readers enough time to announce them
  $(document).ready(function () {
    setTimeout(function () {
      $("#main-alerts-container").removeAttr("role");
    }, 5000);
  });

  // Workaround for max character length on Second Chance Submit on Android
  $(document).ready(function () {
    $("#scratchersEntryCode").keyup(function () {
      limitText("#scratchersEntryCode", 13);
    });
    $("#scratchersTicketID").keyup(function () {
      limitText("#scratchersTicketID", 7);
    });
    $("#SLPCode1").keyup(function () {
      limitText("#SLPCode1", 4);
    });
    $("#SLPCode2").keyup(function () {
      limitText("#SLPCode2", 5);
    });
    $("#SLPCode3").keyup(function () {
      limitText("#SLPCode3", 4);
    });
    $("#F5Code1").keyup(function () {
      limitText("#F5Code1", 4);
    });
    $("#F5Code2").keyup(function () {
      limitText("#F5Code2", 5);
    });
    $("#F5Code3").keyup(function () {
      limitText("#F5Code3", 4);
    });

  });

  // Utility function to limit field length on inputs for workaorund where Android devices not honoring max field length
  function limitText(field, maxChar) {
    if ($(field).val().length > maxChar) {
      $(field).val($(field).val().substr(0, maxChar));
    }
  }


  if ($('body.mobile-device').length && $('body.contact-us-page').length) {
    if ($('.alert').length) {
      $('html, body').animate({
        scrollTop: $(".alert").offset().top - 50
      }, 0);
    }
  }

})(jQuery, window);